<!--
 * @Description: 
 * @Author: chenjiaxin
 * @Date: 2022-05-01 14:53:24
 * @LastEditTime: 2022-05-01 16:14:42
 * @FilePath: \WebSkillExtend\eg15-三叔之和\index2.html
-->
<!--
 * @Description: 
 * @Author: chenjiaxin
 * @Date: 2022-04-25 23:04:04
 * @LastEditTime: 2022-04-25 23:10:01
 * @FilePath: \WebSkillExtend\eg15-三叔之和\index.html
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      var threeSum = function (nums) {
        if (nums.length < 3) return [];

        //从小到大排序  目的避免重复
        nums.sort((a, b) => a - b);
        let result = [];

        for (let index = 0; index < nums.length; index++) {
          // debugger;
          const element = nums[index];
          // 当前元素 和 上一个元素一样的时 跳过这次循环 为了避免重复
          if (element == nums[index - 1]) {
            continue;
          }

          let start = index + 1;
          let end = nums.length - 1;
          while (start < end) {
            // 查找元素
            /**
             * -2,-2,0,1   index=0 start=1  start 不用跳过
             * -2,-2,-2,0,1  index=0  start=2  start指到下标2时,需要跳过,因为此时下标值与start下标1时 值一样。
             */
            if (start - index > 1 && nums[start] == nums[start - 1]) {
              start++;
              continue;
            }
            let sum = element + nums[start] + nums[end];
            if (sum == 0) {
              result.push([element, nums[start], nums[end]]);
              start++;
              end--;
            } else if (sum > 0) {
              end--;
            } else {
              start++;
            }
          }
        }

        return result;
      };
      // var nums = [0, 0, 0];
      // var nums = [1, 1, -2];
      // var nums = [-2, 0, 1, 1, 2];
      // var nums = [3, 0, -2, -1, 1, 2, 1, 0, 2, -3, -3, 0, 2, 4, 5, 4];
      var nums = [-3, -3, -2, -1, 0, 0, 0, 1, 1, 2, 2, 2, 3, 4, 4, 5];
      let result = threeSum(nums);

      console.log(result);
    </script>
  </body>
</html>
